/**
 * SecGroupModules --- Class to control the CRUD of Group and Modules.
 * @author    Luiz Santos
 * @date	  12/08/2013
 */
package com.mbbmap.app.home;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mbbmap.app.exception.LogonException;
import com.mbbmap.app.exception.UniqueKeyViolationException;
import com.mbbmap.app.manager.SystemLogManager;
import com.mbbmap.security.dao.SecGroupsDao;
import com.mbbmap.util.Constants;

public class SecGroupModule {
	
	private static SecGroupModule instance = null;
	
	/**Returns the single instance, creating one if it's the
	* first time this method is called.
	* @return IslamicContractHome. The single instance.
	*/
	public static SecGroupModule getInstance() {
		//thread-safe implementation
		if (instance == null) {
			synchronized (SecGroupModule.class) {
				if (instance == null) {
					instance = new SecGroupModule();
				}
			}
		}
		return instance;
	}

	
	private SecGroupModule() {
		super();
	}
	
	
	
	/** Create the given Groups and Modules
	 *
	 * @param user
	 * @param merchant
	 * @param updatedBy
	 * @param remarks
	 * @return
	 */
	public String createGroupModule (SecGroupsDao secGroup, String merchant, String updatedBy) throws UniqueKeyViolationException, LogonException {

	  boolean success = true;
      Connection connection = null;
      PreparedStatement pstmtInsert = null, pstmtQuery = null;
      int noOfRecords=0;
      String secGroupModule = "";
      
      SystemLogManager sysLogMgr = SystemLogManager.getInstance();;
      DBAccessHome dbh = DBAccessHome.getInstance();
      java.util.Date now = new java.util.Date();
      String allowPwdSameUserId = ParamHome.getInstance().getParamValue(merchant, ParamHome.PARAM_TYPE_SEC, ParamHome.SEC_ALLOW_SAME_USER_ID_PW);

      // get updated by user role
      //UserDao updatedByUserDao = getUser (merchant, updatedBy);

      System.out.println("Start the Group Module insertion into database");
      // insert user record into user table
      String insertSql = "INSERT INTO " + Constants.DB_TBL_GROUPMODULES + " (MODULE_CODE, MODULE_NAME, MER_NAME, CREATED_BY) VALUES(?,?,?,?)";
      System.out.println("The insertSql statement is "+insertSql);
      
      String selectSql = "SELECT MODULE_CODE FROM " + Constants.DB_TBL_GROUPMODULES + " WHERE MODULE_CODE=? ";

      // check
      try {
          connection = dbh.getDBConnection();
          connection.setAutoCommit(false);

          // check that the module to create does not exist
          pstmtQuery =  connection.prepareStatement(selectSql);
          pstmtQuery.setString(1, secGroup.getGroupCode());

          // execute query to get the user DB Id
          ResultSet rs = pstmtQuery.executeQuery();
          if (rs.next()) {
              success = false;
          }
          rs.close();

          if (success == false) {
              throw new UniqueKeyViolationException();
          }

          // Now insert the group record
          pstmtInsert = connection.prepareStatement(insertSql);
	        pstmtInsert.setString(1, secGroup.getGroupCode());
	        pstmtInsert.setString(2, secGroup.getGroupName());
	        pstmtInsert.setString(3, merchant);
	        pstmtInsert.setString(4, updatedBy);
	        
     
	        // execute the insert statement;
	        noOfRecords = pstmtInsert.executeUpdate();

	        if (success && noOfRecords < 1 )
	            success = false;

	        if (success) {
		        pstmtQuery =  connection.prepareStatement(selectSql);
	            pstmtQuery.setString(1, secGroup.getGroupCode());

	            // execute query to get the user DB Id
	            rs = pstmtQuery.executeQuery();
	            if (rs.next()) {
	                secGroupModule= rs.getString(1);
	            }
	            rs.close();
	        }
      } 
      catch (java.sql.SQLException sqle) {
          success  = false;
          sysLogMgr.logMsg("Error in SecGroupModules.createGroupModules() SQL execution : " + insertSql + " \n" + sqle);
          sqle.printStackTrace();
      } finally {
			if (pstmtInsert != null) {
				try {
				    pstmtInsert.close();
				} catch (SQLException e1) {
				}
			}
			if (pstmtQuery != null) {
				try {
				    pstmtQuery.close();
				} catch (SQLException e1) {
				}
			}
			if (!success) {
			    try {
			        connection.rollback();
			    } catch (SQLException sqle) {
		            sysLogMgr.logMsg("Error in connection rollback for SecGroupModles.createGroupModules()\n" + sqle);
		            sqle.printStackTrace();
			    }
			} else {
			    try {
					connection.commit();
					connection.setAutoCommit(true);
			    } catch (SQLException sqle) {
		            sysLogMgr.logMsg("Error in connection commit for SecGroupModles.createGroupModules()\n" + sqle);
		            sqle.printStackTrace();
			    }

			}

			if (connection !=null)
			    dbh.freeDBConnection (connection);
		}

      return secGroupModule;

	}
	
	
	
	
}
